package org.feng.demofx.dao.impl;

import org.feng.demofx.dao.BaseDao;
import org.feng.demofx.dao.AnimalDataPool;
import org.feng.demofx.entity.Animal;
import org.feng.demofx.util.StringUtil;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 动物dao
 *
 * @author feng
 */
public class AnimalDao implements BaseDao<Animal, Long> {

    private static final AnimalDataPool DATA_POOL = new AnimalDataPool();

    @Override
    public boolean update(Animal entity) {
        // 必须传递ID
        Objects.requireNonNull(entity.getId());
        // 查动物
        Animal oldAnimal = selectOne(entity.getId());
        // 修改
        if(StringUtil.isNotEmpty(entity.getName())) {
            oldAnimal.setName(entity.getName());
        }
        if(entity.getAge() != null) {
            oldAnimal.setAge(entity.getAge());
        }
        if(entity.getAnimalType() != null) {
            oldAnimal.setAnimalType(entity.getAnimalType());
        }
        return true;
    }

    @Override
    public List<Animal> listAll() {
        return DATA_POOL.listAll();
    }

    @Override
    public List<Animal> list(Animal entity) {
        return DATA_POOL.listByParam(entity.getId(), entity.getName(), entity.getAnimalType());
    }

    @Override
    public Animal selectOne(Long id) {
        List<Animal> animals = DATA_POOL.listByParam(id, null, null);
        if (animals == null || animals.isEmpty()) {
            return null;
        }
        return animals.get(0);
    }

    @Override
    public boolean delete(Long id) {
        return DATA_POOL.deleteByIds(Collections.singletonList(id));
    }

    @Override
    public boolean delete(List<Long> ids) {
        return DATA_POOL.deleteByIds(ids);
    }

    @Override
    public Animal add(Animal entity) {
        DATA_POOL.insert(entity);
        return entity;
    }
}
